// 通知中心模块 - 负责系统通知和用户提醒的管理

class NotificationCenter {
    constructor() {
        this.notifications = [];
        this.maxNotifications = 100;
        this.unreadCount = 0;
        this.listeners = {};
        this.soundEnabled = true;
        this.desktopNotificationsEnabled = false;
        this.notificationSettings = {
            critical: { sound: true, desktop: true, keep: true },
            high: { sound: true, desktop: true, keep: false },
            medium: { sound: false, desktop: true, keep: false },
            low: { sound: false, desktop: false, keep: false },
            info: { sound: false, desktop: false, keep: false },
            success: { sound: false, desktop: false, keep: false },
            warning: { sound: false, desktop: true, keep: false },
            error: { sound: true, desktop: true, keep: false }
        };
        
        // 预加载声音文件
        this.sounds = {};
    }

    // 初始化通知中心
    init() {
        console.log('通知中心初始化...');
        
        // 检查并请求桌面通知权限
        this.checkDesktopNotificationPermission();
        
        // 尝试加载设置
        this.loadSettings();
        
        // 初始化通知面板UI
        this.initNotificationPanel();
        
        console.log('通知中心初始化完成');
    }

    // 检查桌面通知权限
    checkDesktopNotificationPermission() {
        if (!('Notification' in window)) {
            console.warn('当前浏览器不支持桌面通知');
            return;
        }
        
        if (Notification.permission === 'granted') {
            this.desktopNotificationsEnabled = true;
            console.log('桌面通知已启用');
        } else if (Notification.permission !== 'denied') {
            // 请求权限
            Notification.requestPermission().then(permission => {
                if (permission === 'granted') {
                    this.desktopNotificationsEnabled = true;
                    console.log('桌面通知已启用');
                }
            });
        }
    }

    // 初始化通知面板UI
    initNotificationPanel() {
        // 创建通知计数器元素
        const notificationCounter = document.createElement('span');
        notificationCounter.id = 'notification-counter';
        notificationCounter.className = 'notification-counter';
        notificationCounter.textContent = '0';
        notificationCounter.style.display = 'none';
        
        // 尝试将计数器添加到通知按钮
        const notificationBtn = document.querySelector('.notification-btn');
        if (notificationBtn) {
            notificationBtn.appendChild(notificationCounter);
        }
        
        // 添加通知面板事件监听
        this.setupNotificationPanelEvents();
    }

    // 设置通知面板事件监听
    setupNotificationPanelEvents() {
        const notificationBtn = document.querySelector('.notification-btn');
        const notificationPanel = document.getElementById('notification-panel');
        
        if (notificationBtn && notificationPanel) {
            // 切换通知面板显示
            notificationBtn.addEventListener('click', () => {
                notificationPanel.classList.toggle('visible');
                
                // 点击按钮时标记所有通知为已读
                if (notificationPanel.classList.contains('visible')) {
                    this.markAllAsRead();
                }
            });
            
            // 点击面板外部关闭面板
            document.addEventListener('click', (e) => {
                if (!notificationBtn.contains(e.target) && 
                    !notificationPanel.contains(e.target)) {
                    notificationPanel.classList.remove('visible');
                }
            });
        }
    }

    // 添加通知
    addNotification(options) {
        const notification = {
            id: `notification_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            title: options.title || '通知',
            message: options.message || '',
            type: options.type || 'info',
            category: options.category || '系统',
            icon: options.icon || this.getTypeIcon(options.type),
            timestamp: Date.now(),
            read: false,
            keep: options.keep || this.notificationSettings[options.type]?.keep || false,
            data: options.data || {},
            actions: options.actions || [],
            dismissible: options.dismissible !== false,
            duration: options.duration || this.getNotificationDuration(options.type)
        };
        
        // 添加到通知列表
        this.notifications.unshift(notification); // 新通知放在前面
        
        // 增加未读计数
        this.unreadCount++;
        
        // 限制通知数量
        this.limitNotifications();
        
        // 更新UI
        this.updateNotificationUI();
        
        // 触发通知事件
        this.emit('notification:added', notification);
        
        // 根据设置处理声音和桌面通知
        this.processNotificationSettings(notification);
        
        // 如果可自动关闭，设置定时器
        if (notification.dismissible && notification.duration > 0) {
            setTimeout(() => {
                this.dismissNotification(notification.id);
            }, notification.duration);
        }
        
        return notification;
    }

    // 获取通知类型图标
    getTypeIcon(type) {
        const icons = {
            critical: 'error',
            high: 'priority_high',
            medium: 'warning',
            low: 'info',
            info: 'info',
            success: 'check_circle',
            warning: 'warning',
            error: 'error_outline'
        };
        
        return icons[type] || 'info';
    }

    // 获取通知显示时长
    getNotificationDuration(type) {
        const durations = {
            critical: 0, // 不自动关闭
            high: 0, // 不自动关闭
            medium: 10000, // 10秒
            low: 5000, // 5秒
            info: 5000, // 5秒
            success: 3000, // 3秒
            warning: 8000, // 8秒
            error: 10000 // 10秒
        };
        
        return durations[type] || 5000;
    }

    // 根据设置处理通知
    processNotificationSettings(notification) {
        const settings = this.notificationSettings[notification.type] || {};
        
        // 播放声音
        if (settings.sound && this.soundEnabled) {
            this.playNotificationSound(notification.type);
        }
        
        // 显示桌面通知
        if (settings.desktop && this.desktopNotificationsEnabled && 'Notification' in window) {
            this.showDesktopNotification(notification);
        }
    }

    // 播放通知声音
    playNotificationSound(type) {
        try {
            // 这里应该根据不同类型播放不同的声音
            // 为了简化，我们使用Web Audio API生成简单的提示音
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            // 根据通知类型设置不同频率
            if (type === 'critical' || type === 'error') {
                oscillator.frequency.value = 800;
                gainNode.gain.value = 0.3;
                oscillator.start();
                oscillator.stop(audioContext.currentTime + 0.5);
            } else if (type === 'warning' || type === 'high') {
                oscillator.frequency.value = 600;
                gainNode.gain.value = 0.2;
                oscillator.start();
                oscillator.stop(audioContext.currentTime + 0.3);
            } else {
                oscillator.frequency.value = 400;
                gainNode.gain.value = 0.1;
                oscillator.start();
                oscillator.stop(audioContext.currentTime + 0.2);
            }
        } catch (error) {
            console.warn('播放通知声音失败:', error);
        }
    }

    // 显示桌面通知
    showDesktopNotification(notification) {
        try {
            const options = {
                body: notification.message,
                icon: '/assets/images/notification-icon.png',
                badge: '/assets/images/notification-badge.png',
                requireInteraction: notification.type === 'critical' || notification.type === 'high',
                vibrate: [200, 100, 200],
                data: { notificationId: notification.id }
            };
            
            const desktopNotification = new Notification(notification.title, options);
            
            // 点击桌面通知时聚焦到应用并标记为已读
            desktopNotification.onclick = () => {
                window.focus();
                this.markAsRead(notification.id);
                
                // 如果有相关动作，执行第一个动作
                if (notification.actions && notification.actions.length > 0) {
                    this.executeNotificationAction(notification.actions[0], notification.data);
                }
            };
        } catch (error) {
            console.warn('显示桌面通知失败:', error);
        }
    }

    // 限制通知数量
    limitNotifications() {
        // 移除旧通知，但保留需要保留的通知
        const keepNotifications = this.notifications.filter(n => n.keep);
        const nonKeepNotifications = this.notifications.filter(n => !n.keep);
        
        // 计算可以保留的非保留通知数量
        const maxNonKeepNotifications = Math.max(0, this.maxNotifications - keepNotifications.length);
        
        // 保留最新的非保留通知
        const filteredNonKeepNotifications = nonKeepNotifications.slice(0, maxNonKeepNotifications);
        
        // 重新组合通知列表
        this.notifications = [...keepNotifications, ...filteredNonKeepNotifications];
    }

    // 更新通知UI
    updateNotificationUI() {
        // 更新计数器
        const counterElement = document.getElementById('notification-counter');
        if (counterElement) {
            if (this.unreadCount > 0) {
                counterElement.textContent = this.unreadCount > 99 ? '99+' : this.unreadCount;
                counterElement.style.display = 'inline';
            } else {
                counterElement.style.display = 'none';
            }
        }
        
        // 更新通知面板
        this.updateNotificationPanel();
    }

    // 更新通知面板
    updateNotificationPanel() {
        const notificationPanel = document.getElementById('notification-panel');
        if (!notificationPanel) return;
        
        const notificationList = notificationPanel.querySelector('.notification-list');
        if (!notificationList) return;
        
        // 清空列表
        notificationList.innerHTML = '';
        
        // 如果没有通知，显示空状态
        if (this.notifications.length === 0) {
            const emptyState = document.createElement('div');
            emptyState.className = 'notification-empty-state';
            emptyState.innerHTML = `
                <i class="material-icons">notifications_off</i>
                <p>暂无通知</p>
            `;
            notificationList.appendChild(emptyState);
            return;
        }
        
        // 添加通知项
        this.notifications.forEach(notification => {
            const notificationItem = this.createNotificationElement(notification);
            notificationList.appendChild(notificationItem);
        });
    }

    // 创建通知元素
    createNotificationElement(notification) {
        const item = document.createElement('div');
        item.className = `notification-item ${notification.type} ${notification.read ? 'read' : 'unread'}`;
        item.dataset.id = notification.id;
        
        // 构建操作按钮HTML
        let actionsHtml = '';
        if (notification.actions && notification.actions.length > 0) {
            actionsHtml = `<div class="notification-actions">
                ${notification.actions.map(action => `
                    <button class="notification-action" data-action="${action.action}">
                        ${action.label}
                    </button>
                `).join('')}
            </div>`;
        }
        
        // 构建通知内容HTML
        item.innerHTML = `
            <div class="notification-icon">
                <i class="material-icons">${notification.icon}</i>
            </div>
            <div class="notification-content">
                <div class="notification-header">
                    <h4>${notification.title}</h4>
                    <span class="notification-time">${this.formatTime(notification.timestamp)}</span>
                </div>
                <p class="notification-message">${notification.message}</p>
                ${actionsHtml}
            </div>
            ${notification.dismissible ? `
                <button class="notification-dismiss" title="关闭">
                    <i class="material-icons">close</i>
                </button>
            ` : ''}
        `;
        
        // 添加事件监听
        // 点击通知标记为已读
        item.addEventListener('click', (e) => {
            if (!e.target.closest('.notification-action') && 
                !e.target.closest('.notification-dismiss')) {
                this.markAsRead(notification.id);
            }
        });
        
        // 点击操作按钮
        item.querySelectorAll('.notification-action').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const actionType = btn.dataset.action;
                const action = notification.actions.find(a => a.action === actionType);
                if (action) {
                    this.executeNotificationAction(action, notification.data);
                }
            });
        });
        
        // 点击关闭按钮
        const dismissBtn = item.querySelector('.notification-dismiss');
        if (dismissBtn) {
            dismissBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                this.dismissNotification(notification.id);
            });
        }
        
        return item;
    }

    // 执行通知操作
    executeNotificationAction(action, data) {
        console.log(`执行通知操作: ${action.action}`, action.data || data);
        
        // 触发操作事件
        this.emit(`notification:action:${action.action}`, {
            action,
            data: { ...data, ...action.data }
        });
    }

    // 标记通知为已读
    markAsRead(notificationId) {
        const notification = this.notifications.find(n => n.id === notificationId);
        if (notification && !notification.read) {
            notification.read = true;
            this.unreadCount = Math.max(0, this.unreadCount - 1);
            
            // 更新UI
            this.updateNotificationUI();
            
            // 触发事件
            this.emit('notification:read', notification);
            
            return true;
        }
        
        return false;
    }

    // 标记所有通知为已读
    markAllAsRead() {
        let count = 0;
        
        this.notifications.forEach(notification => {
            if (!notification.read) {
                notification.read = true;
                count++;
            }
        });
        
        this.unreadCount = 0;
        
        // 更新UI
        this.updateNotificationUI();
        
        // 触发事件
        if (count > 0) {
            this.emit('notification:allRead', { count });
        }
        
        return count;
    }

    // 关闭通知
    dismissNotification(notificationId) {
        const index = this.notifications.findIndex(n => n.id === notificationId);
        if (index !== -1) {
            const notification = this.notifications[index];
            
            // 移除通知
            this.notifications.splice(index, 1);
            
            // 如果是未读通知，减少未读计数
            if (!notification.read) {
                this.unreadCount = Math.max(0, this.unreadCount - 1);
            }
            
            // 更新UI
            this.updateNotificationUI();
            
            // 触发事件
            this.emit('notification:dismissed', notification);
            
            return true;
        }
        
        return false;
    }

    // 关闭所有通知
    dismissAllNotifications() {
        const count = this.notifications.length;
        this.notifications = [];
        this.unreadCount = 0;
        
        // 更新UI
        this.updateNotificationUI();
        
        // 触发事件
        if (count > 0) {
            this.emit('notification:allDismissed', { count });
        }
        
        return count;
    }

    // 获取通知
    getNotifications(filter = {}) {
        let notifications = [...this.notifications];
        
        // 应用过滤条件
        if (filter.type) {
            notifications = notifications.filter(n => n.type === filter.type);
        }
        
        if (filter.read !== undefined) {
            notifications = notifications.filter(n => n.read === filter.read);
        }
        
        if (filter.category) {
            notifications = notifications.filter(n => n.category === filter.category);
        }
        
        if (filter.limit) {
            notifications = notifications.slice(0, filter.limit);
        }
        
        return notifications;
    }

    // 更新通知设置
    updateSettings(settings) {
        this.notificationSettings = { ...this.notificationSettings, ...settings };
        this.saveSettings();
        
        // 触发事件
        this.emit('notification:settingsUpdated', this.notificationSettings);
        
        return true;
    }

    // 设置声音开关
    setSoundEnabled(enabled) {
        this.soundEnabled = enabled;
        this.saveSettings();
        return true;
    }

    // 设置桌面通知开关
    setDesktopNotificationsEnabled(enabled) {
        if (enabled && Notification.permission !== 'granted') {
            // 如果用户尝试启用桌面通知但尚未获得权限，请求权限
            Notification.requestPermission().then(permission => {
                this.desktopNotificationsEnabled = permission === 'granted';
                this.saveSettings();
            });
        } else {
            this.desktopNotificationsEnabled = enabled;
            this.saveSettings();
        }
        
        return this.desktopNotificationsEnabled;
    }

    // 保存设置到本地存储
    saveSettings() {
        try {
            const settings = {
                notificationSettings: this.notificationSettings,
                soundEnabled: this.soundEnabled,
                desktopNotificationsEnabled: this.desktopNotificationsEnabled
            };
            
            localStorage.setItem('notification_settings', JSON.stringify(settings));
            return true;
        } catch (error) {
            console.error('保存通知设置失败:', error);
            return false;
        }
    }

    // 从本地存储加载设置
    loadSettings() {
        try {
            const storedSettings = localStorage.getItem('notification_settings');
            if (storedSettings) {
                const settings = JSON.parse(storedSettings);
                
                if (settings.notificationSettings) {
                    this.notificationSettings = settings.notificationSettings;
                }
                
                if (settings.soundEnabled !== undefined) {
                    this.soundEnabled = settings.soundEnabled;
                }
                
                if (settings.desktopNotificationsEnabled !== undefined) {
                    this.desktopNotificationsEnabled = settings.desktopNotificationsEnabled;
                }
                
                return true;
            }
        } catch (error) {
            console.error('加载通知设置失败:', error);
        }
        
        return false;
    }

    // 格式化时间
    formatTime(timestamp) {
        const now = Date.now();
        const diff = now - timestamp;
        
        // 小于1分钟
        if (diff < 60 * 1000) {
            return '刚刚';
        }
        
        // 小于1小时
        if (diff < 60 * 60 * 1000) {
            return `${Math.floor(diff / (60 * 1000))}分钟前`;
        }
        
        // 小于24小时
        if (diff < 24 * 60 * 60 * 1000) {
            return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
        }
        
        // 大于等于24小时，显示日期
        return new Date(timestamp).toLocaleDateString();
    }

    // 注册监听器
    on(event, callback) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
        
        return () => {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        };
    }

    // 触发事件
    emit(event, data) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`处理${event}事件时出错:`, error);
                }
            });
        }
    }

    // 发送预定义的系统通知
    sendSystemNotification(type, message, options = {}) {
        const titles = {
            info: '系统信息',
            success: '操作成功',
            warning: '警告',
            error: '错误',
            critical: '严重错误'
        };
        
        return this.addNotification({
            title: titles[type] || '系统通知',
            message,
            type,
            category: '系统',
            ...options
        });
    }
}

// 创建并注册通知中心实例
const notificationCenter = new NotificationCenter();
realTimeSystem.registerModule('notificationCenter', notificationCenter);

// 导出通知中心
window.notificationCenter = notificationCenter;